<?php

namespace App\Http\Api\V1\Blls;

use App\Http\Common\Facade\PostCategoryFacade;
use App\Http\Common\Facade\PostFacade;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class PostBll
{
    public static function getPostList($categoryId, $limit, $order, $keyword = null)
    {
        $list = PostFacade::getByCondition($categoryId, $limit, $order, $keyword);
        $postList = [];
        $categoryIds = [];
        foreach ($list as $post) {
            $postList[] = [
                'id' => $post->id,
                'title' => $post->title,
                'category' => $post->category_id,
            ];
            $categoryIds[] = $post->category_id;
        }

        $categoryIdNameMap = self::getCategoryNames($categoryIds);

        array_walk($postList, function (&$post) use ($categoryIdNameMap) {
            $post['category'] = $categoryIdNameMap[$post['category']] ?? '';
        });

        return $postList;
    }

    public static function getPostDetail($postId)
    {
        $post = PostFacade::getOneById($postId);
        if ($post) {
            $category = PostCategoryFacade::getOneById($post->category_id);
            if (!$category) {
                throw new ModelNotFoundException('Category not found.');
            }

            return [
                'id' => $post->id,
                'title' => $post->title,
                'content' => $post->content,
                'category' => $category->name,
            ];
        } else {
            throw new ModelNotFoundException('Post not found.');
        }
    }

    public static function getPostCategoryList($limit, $isDefault, $order)
    {
        $list = PostCategoryFacade::getByCondition($limit, $isDefault, $order);
        $catList = [];
        foreach ($list as $cat) {
            $catList[] = [
                'id' => $cat->id,
                'name' => $cat->name,
                'icon' => $cat->icon,
            ];
        }

        return $catList;
    }

    private static function getCategoryNames($categoryIds)
    {
        $categories = PostCategoryFacade::getByIds($categoryIds);

        $categoryIdNameMap = [];
        foreach ($categories as $category) {
            $categoryIdNameMap[$category->id] = $category->name;
        }

        return $categoryIdNameMap;
    }
}
